package com.service.quartz.service;

import com.service.quartz.constant.TaskConstant;
import com.service.quartz.dao.TaskDao;
import com.service.quartz.dto.JobDto;
import com.service.quartz.dto.TaskDto;
import com.service.quartz.event.CreateJobEvent;
import com.service.quartz.event.RemoveJobEvent;
import com.service.quartz.mapper.TaskMapper;
import com.service.quartz.model.TaskModel;
import com.tool.base.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class JobService {
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private ApplicationContext context;

    public TaskDto createJob(JobDto jobDto) {
        TaskModel taskModel = new TaskModel();
        taskModel.setNotifyUrl(jobDto.getUrl());
        taskModel.setNotifyData(jobDto.getContentData());
        taskModel.setMaxRetry(jobDto.getMaxRetry());
        taskModel.setCronTab(jobDto.getCronTab());
        taskModel.setTitle(jobDto.getTitle());
        taskModel.setNotifyState(TaskConstant.NOTIFY_STATE_READY);
        taskModel.setNotifyResult("未开始");
        taskModel = taskDao.save(taskModel);
        context.publishEvent(new CreateJobEvent(this, taskModel));
        return taskMapper.modelToDto(taskModel);
    }

    public void removeJob(int id) {
        TaskModel taskModel = taskDao.getById(id);
        if (null == taskModel) {
            throw new ApiException("任务不存在", 404);
        }
        taskDao.delete(taskModel.getId());
        context.publishEvent(new RemoveJobEvent(this, taskModel));
    }

    public TaskDto getJob(int id) {
        return taskMapper.modelToDto(taskDao.getById(id));
    }
}
